package io.gitee.kotle.player.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Build
import android.os.Bundle
import android.view.WindowManager
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.media3.common.MediaItem
import io.gitee.kotle.player.core.IPlayer
import io.gitee.kotle.player.core.bindDownloadHelper
import io.gitee.kotle.player.core.impl.exoplayer.IExoPlayerListener
import io.gitee.kotle.player.core.impl.exoplayer.IExoPlayerMode
import io.gitee.kotle.player.core.isPlaying
import io.gitee.kotle.player.core.playModel
import io.gitee.kotle.player.download.IPlayerDownload
import io.gitee.kotle.player.ui.bindPlayerView
import io.gitee.kotle.player.ui.view.exo.ExoPlayerViewConfig
import io.gitee.kotle.player.ui.view.exo.ExoRootView
import kotlinx.coroutines.CoroutineScope

/**
 *
 * 描述：
 *
 * 创建人：jiale.wei
 * 创建时间：2023/4/21 21:59
 *
 */
class PlayerActivity : Activity(), IExoPlayerListener<IExoPlayerMode> {
    companion object {
        private const val KEY_VIDEO_WIDTH = "KEY_VIDEO_WIDTH"
        private const val KEY_VIDEO_HEIGHT = "KEY_VIDEO_WIDTH"
        private const val KEY_MEDIA_ID = "KEY_MEDIA_ID"


        fun start(
            context: Context,
            mediaId: String,
            videoWidth: Int = 0,
            videoHeight: Int = 0,
            title: String? = null
        ) {
            val intent = Intent(context, PlayerActivity::class.java)
            intent.putExtra(KEY_MEDIA_ID, mediaId)
            intent.putExtra(KEY_VIDEO_WIDTH, videoWidth)
            intent.putExtra(KEY_VIDEO_HEIGHT, videoHeight)
            intent.putExtra(Intent.EXTRA_TITLE, title)
            context.startActivity(intent)
        }
    }

    private var player: IPlayer<MediaItem, IExoPlayerMode>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        fullScreen()
        player = createPlayer()
    }

    private fun createPlayer(): IPlayer<MediaItem, IExoPlayerMode>? {
        val intent = this.intent ?: return null
        val mediaId = intent.getStringExtra(KEY_MEDIA_ID) ?: intent.dataString ?: return null
        val title = intent.getStringExtra(Intent.EXTRA_TITLE)
        val videoWidth = intent.getIntExtra(KEY_VIDEO_WIDTH, 0)
        val videoHeight = intent.getIntExtra(KEY_VIDEO_HEIGHT, 0)
        //支持资源下载
        val player = IPlayer.exoPlayer<IExoPlayerMode>(this)
        //绑定下载器
        val downloader = player.bindDownloadHelper(IPlayerDownload.exoPlayerDownload(this))
        //开始启动下载资源
        downloader.resumeDownloads()
        val view = createPlayerView()
        view.bindPlayerView(ExoPlayerViewConfig(player).also {
            it.singleTapConfirmed.value = true
        })
        if (videoWidth > 0 && videoHeight > 0) {
            view.binding.exoPlayerTextureView.onVideoSizeChange(
                player,
                videoWidth,
                videoHeight,
                0,
                0f
            )
        }
        updateOrientation(videoWidth, videoWidth)
        player.addListener(object : IExoPlayerListener<IExoPlayerMode> {
            override fun onModelState(
                player: IPlayer<MediaItem, IExoPlayerMode>,
                state: IPlayer.ModelState
            ) {
                super.onModelState(player, state)
                view.keepScreenOn = player.isPlaying
            }

            override fun onVideoSizeChange(
                player: IPlayer<MediaItem, IExoPlayerMode>,
                width: Int,
                height: Int,
                unAppliedRotationDegrees: Int,
                pixelWidthHeightRatio: Float
            ) {
                super.onVideoSizeChange(
                    player,
                    width,
                    height,
                    unAppliedRotationDegrees,
                    pixelWidthHeightRatio
                )
                updateOrientation(width, height)
            }
        })
        player.startTick()
        val model = object : IExoPlayerMode {
            override suspend fun getMediaId(
                scope: CoroutineScope,
                player: IPlayer<MediaItem, *>
            ): String {
                return mediaId
            }

            override suspend fun getTitle(
                scope: CoroutineScope,
                player: IPlayer<MediaItem, *>
            ): String? {
                return title
            }
        }
        //使用post。保证所有view准备就绪再开始播放
        view.post {
            player.playModel(model)
        }
        return player
    }

    /**
     * 创建和添加view
     */
    private fun createPlayerView(): ExoRootView {
        val view = ExoRootView(this)
        setContentView(view)
        return view
    }

    /**
     * 根据宽高设置视频方向
     */
    private fun updateOrientation(videoWidth: Int, videoHeight: Int) {
        try {
            requestedOrientation = if (videoWidth <= 0 || videoHeight <= 0) {
                ActivityInfo.SCREEN_ORIENTATION_SENSOR
            } else {
                if (videoWidth > videoHeight) {
                    ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
                } else {
                    ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
                }
            }
        } catch (e: Throwable) {
            e.printStackTrace()
        }
    }


    private fun fullScreen() {
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        val insetsController = WindowCompat.getInsetsController(window, window.decorView)
        insetsController.systemBarsBehavior =
            WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            window.attributes.layoutInDisplayCutoutMode =
                WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
        }
        insetsController.hide(WindowInsetsCompat.Type.systemBars())
        WindowCompat.setDecorFitsSystemWindows(window, false)
    }

    override fun onStop() {
        super.onStop()
        player?.pause()
    }

    override fun onDestroy() {
        player?.release()
        super.onDestroy()
    }
}